package com.ddc.study.net;

import com.ddc.study.base.BaseApplication;
import com.ddc.study.entity.Article;
import com.ddc.study.entity.Banner;
import com.ddc.study.entity.CollectWebsite;
import com.ddc.study.entity.Collection;
import com.ddc.study.entity.Friend;
import com.ddc.study.entity.HotKey;
import com.ddc.study.entity.MainData;
import com.ddc.study.entity.Navigation;
import com.ddc.study.entity.Tree;
import com.ddc.study.entity.User;
import com.ddc.study.net.response.BaseResponse;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.IntRange;
import androidx.annotation.Nullable;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created on 2018/3/28.
 *
 * @author lshun
 * @version 1.0
 */
public class NetworkUtil {
    private static final int CONNECT_TIME_OUT = 5;
    private static final int READ_TIME_OUT = 5;

    public static final String BASE_URL = "https://www.wanandroid.com/";

    private NetworkUtil() {
    }

    private static final ApiService sService;

    private static final ApiService sCookieService;

    static {
        OkHttpClient sClient = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
                .addInterceptor(new LogInterceptor())
                .build();
        Retrofit sRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                .client(sClient)
                .build();
        sService = sRetrofit.create(ApiService.class);

        OkHttpClient sCookieClient = new OkHttpClient.Builder()
                .cookieJar(BaseApplication.getInstance().getCookieManager())
                .connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
                .addInterceptor(new LogInterceptor())
                .build();

        Retrofit sCookieRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                .client(sCookieClient)
                .build();

        sCookieService = sCookieRetrofit.create(ApiService.class);
    }

    public static ApiService getService() {
        return sService;
    }

    public static ApiService getCookieService() {
        return sCookieService;
    }

    @Nullable
    public static List<Banner> getBanner() {
        try {
            BaseResponse<List<Banner>> body = sService.getBanner().execute().body();
            if (body != null && body.isSuccess()) {
                return body.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取首页文章列表
     *
     * @param page 页码(从0开始)
     * @return 文章列表信息
     */
    @Nullable
    public static MainData<Article> getMainArticleList(int page) {
        if (page < 0) return null;
        try {
            //使用cookie可以判断文章是否被收集
            BaseResponse<MainData<Article>> body = sCookieService.getArticleList(page).execute().body();
            if (body != null && body.isSuccess()) {
                return body.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 常用网站
     *
     * @return 常用网站列表
     */
    @Nullable
    public static List<Friend> getFriendSite() {
        try {
            BaseResponse<List<Friend>> body = sService.getFriendSite().execute().body();
            if (body != null && body.isSuccess()) {
                return body.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 搜索热词
     *
     * @return 搜索热词列表
     */
    @Nullable
    public static List<HotKey> getHotKey() {
        try {
            BaseResponse<List<HotKey>> body = sService.getHotKey().execute().body();
            if (body != null && body.isSuccess()) {
                return body.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Call<BaseResponse<User>> login(String username, String password) {
        return sCookieService.login(username, password);
    }

    public static Call<BaseResponse<User>> register(String username, String password, String rePassword) {
        return sCookieService.register(username, password, rePassword);
    }

    @Nullable
    public static List<Navigation> getNavigationData() {
        try {
            BaseResponse<List<Navigation>> body = sService.getNavigationData().execute().body();
            if (body != null && body.isSuccess()) {
                return body.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Nullable
    public static List<Tree> getTreeData() {
        try {
            BaseResponse<List<Tree>> body = sService.getTreeData().execute().body();
            if (body != null && body.isSuccess()) {
                return body.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Nullable
    public static MainData<Article> getTreeArticle(int page, int cid) {
        try {
            BaseResponse<MainData<Article>> body = sService.getTreeArticle(page, String.valueOf(cid)).execute().body();
            if (body != null && body.isSuccess()) {
                return body.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static Call<BaseResponse<List<Tree>>> getProjectTree() {
        return sService.getProjectTree();
    }

    public static Call<BaseResponse<MainData<Article>>> getProjectData(int page, int cid) {
        return sService.getProjectData(page, String.valueOf(cid));
    }

    /**
     * @param page    页码
     * @param keyword 关键字
     * @return 查询结果
     */
    @Nullable
    public static MainData<Article> queryKey(int page, String keyword) {
        if (page < 0 || keyword == null || keyword.isEmpty()) return null;
        try {
            BaseResponse<MainData<Article>> body = sCookieService.queryArticle(page, keyword).execute().body();
            if (body != null && body.isSuccess()) {
                return body.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Call<BaseResponse<MainData<Collection>>> getCollectArticle(@IntRange(from = 1) int page) {
        return sCookieService.getCollectArticle(page - 1);
    }

    public static Call<BaseResponse<Object>> collectInnerArticle(int id) {
        return sCookieService.collectInnerArticle(id);
    }

    public static boolean collectOuterArticle(String title, String author, String link) {
        try {
            BaseResponse<Object> body = sCookieService.collectOuterArticle(title, author, link).execute().body();
            return body != null && body.isSuccess();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static Call<BaseResponse<Object>> unCollectArticle1(int id) {
        return sCookieService.unCollectArticle1(id);
    }

    public static boolean unCollectArticle2(int id, int originId) {
        try {
            BaseResponse<Object> body = sCookieService.unCollectArticle2(id, originId).execute().body();
            return body != null && body.isSuccess();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Nullable
    public static List<CollectWebsite> getCollectList() {
        try {
            BaseResponse<List<CollectWebsite>> body = sCookieService.getCollectList().execute().body();
            if (body != null && body.isSuccess()) {
                return body.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 收藏网址
     */
    @Nullable
    public static CollectWebsite collectLink(String name, String link) {
        try {
            BaseResponse<CollectWebsite> body = sCookieService.collectLink(name, link).execute().body();
            if (body != null && body.isSuccess()) {
                return body.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 编辑收藏网站
     */
    @Nullable
    public static CollectWebsite editCollectLink(int id, String name, String link) {
        try {
            BaseResponse<CollectWebsite> body = sCookieService.editCollectLink(String.valueOf(id), name, link).execute().body();
            if (body != null && body.isSuccess()) {
                return body.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除收藏网站
     */
    public static boolean deleteLink(int id) {
        try {
            BaseResponse<Object> body = sCookieService.deleteLink(String.valueOf(id)).execute().body();
            return body != null && body.isSuccess();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
